<?php
namespace RPC;
use Config;
use Yar_Client;
use Yar_Server;

/**
 * Yar RPC
 */
class YarRPC implements RpcInterface
{
    protected Yar_Client $client;

    protected array $config;

    public function __construct()
    {
        if (!extension_loaded("yar")) die("yar extension is not installed!");
        $this->config = Config::get("rpc");
    }

    /**
     * 初始化Yar 服务端
     * @param object|null $object
     * @return bool
     */
    public function server(?object $object): bool
    {
        $server = new Yar_Server($object);
        return $server->handle();
    }

    /**
     * 初始化Yar 客户端
     * @param string|null $object
     * @return $this
     */
    public function client(?string $object): YarRPC
    {
        $this->client = new Yar_Client($this->config['host'].'/'.$object);
        return $this;
    }

    /**
     * 设置配置
     * @param array|string|null $options
     * @param mixed|null $value
     * @return Yar_Client
     */
    public function setOpt(array|string|null $options, mixed $value = null): Yar_Client
    {
        if (is_array($options)) {
            foreach ($options as $key => $value) {
                $this->client->setOpt($key, $value);
            }
        }else {
            $this->client->setOpt($options, $value);
        }
        return $this->client;
    }

    /**
     * 设置token
     * @param string $token
     * @return Yar_Client
     */
    public function token(string $token): Yar_Client
    {
        $this->client->setOpt(YAR_OPT_TOKEN, $token);
        return $this->client;
    }

    /**
     * 获取配置
     * @param int|string $type
     * @return mixed
     */
    public function getOpt(int|string $type): mixed
    {
        // TODO: Implement getOpt() method.
        return $this->client->getOpt($type);
    }
}
